<template>
  <div class="nav-container">
    <!-- Logo区域 -->
    <div class="logo-section">
      <img src="@/assets/photos/dns-logo.png" alt="Logo">
    </div>

    <!-- 导航菜单 -->
    <el-menu
        class="nav-menu"
        :collapse="false"
        :default-active="activeMenu"
        background-color="transparent"
        text-color="rgba(255, 255, 255, 0.7)"
        active-text-color="#ffffff"
        router
    >
      <el-menu-item index="/dashboard">
        <el-icon><PieChart /></el-icon>
        <template #title>dns安全态势总览</template>
      </el-menu-item>

      <el-sub-menu index="single">
        <template #title>
          <div class="menu-item">
            <el-icon><Search /></el-icon>
            <span>单个探测</span>
          </div>
        </template>
        <el-menu-item index="/dohSingle">
          <div class="submenu-item">
            <span class="dot"></span>
            <span>doh</span>
          </div>
        </el-menu-item>
        <el-menu-item index="/dotSingle">
          <div class="submenu-item">
            <span class="dot"></span>
            <span>dot</span>
          </div>
        </el-menu-item>
        <el-menu-item index="/dnssecSingle">
          <div class="submenu-item">
            <span class="dot"></span>
            <span>dnssec</span>
          </div>
        </el-menu-item>
      </el-sub-menu>

      <el-sub-menu index="batch">
        <template #title>
          <div class="menu-item">
            <el-icon><Setting /></el-icon>
            <span>批量探测</span>
          </div>
        </template>
        <el-menu-item index="/dohBatch">
          <div class="submenu-item">
            <span class="dot"></span>
            <span>doh</span>
          </div>
        </el-menu-item>
        <el-menu-item index="/dotBatch">
          <div class="submenu-item">
            <span class="dot"></span>
            <span>dot</span>
          </div>
        </el-menu-item>
        <el-menu-item index="/dnssecBatch">
          <div class="submenu-item">
            <span class="dot"></span>
            <span>dnssec</span>
          </div>
        </el-menu-item>
      </el-sub-menu>

      <el-menu-item index="/custom-scan">
        <el-icon><DocumentAdd /></el-icon>
        <template #title>定制扫描</template>
      </el-menu-item>

      <el-menu-item index="/profile">
        <el-icon><User /></el-icon>
        <template #title>个人中心</template>
      </el-menu-item>
    </el-menu>

    <!-- 用户信息区域 -->
    <div class="user-section">
      <div class="user-info" v-if="userInfo">
        <div class="user-avatar">
          <img :src="userInfo.avatarUrl || '/images/avatars/default-user.png'" :alt="userInfo.username">
        </div>
        <div class="user-details">
          <div class="username">{{ userInfo.username }}</div>
          <div class="user-role">{{ getRoleText(userInfo.userRole) }}</div>
        </div>
      </div>
      <div class="user-actions">
        <el-button type="text" @click="logout" class="logout-btn">
          <el-icon><Switch /></el-icon>
          <span>退出登录</span>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import {
  PieChart,
  Search,
  Setting,
  Switch,
  User,
  DocumentAdd
} from '@element-plus/icons-vue'
import { auth } from '@/utils/auth'

const route = useRoute()
const router = useRouter()

// 用户信息
const userInfo = ref(null)

// 计算当前激活的菜单项
const activeMenu = computed(() => {
  return route.path
})

// 监听localStorage变化的函数
const handleStorageChange = (e) => {
  if (e.key === 'user' && e.newValue) {
    try {
      userInfo.value = JSON.parse(e.newValue)
      console.log('Navigator: 用户信息已更新', userInfo.value)
    } catch (error) {
      console.error('Navigator: 解析用户信息失败', error)
    }
  }
}

// 获取用户信息
onMounted(() => {
  userInfo.value = auth.getUser()
  // 监听localStorage变化
  window.addEventListener('storage', handleStorageChange)
  
  // 定期检查用户信息变化（用于同页面更新）
  const checkUserInfo = () => {
    const currentUser = auth.getUser()
    if (currentUser && JSON.stringify(currentUser) !== JSON.stringify(userInfo.value)) {
      userInfo.value = currentUser
      console.log('Navigator: 检测到用户信息变化', userInfo.value)
    }
  }
  
  // 每秒检查一次用户信息变化
  const intervalId = setInterval(checkUserInfo, 1000)
  
  // 保存intervalId以便清理
  onBeforeUnmount(() => {
    window.removeEventListener('storage', handleStorageChange)
    clearInterval(intervalId)
  })
})

// 获取角色文本
const getRoleText = (role) => {
  const roleMap = {
    'admin': '管理员',
    'user': '普通用户'
  }
  return roleMap[role] || role
}

// 退出登录
const logout = async () => {
  try {
    await ElMessageBox.confirm('确认退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 清除认证信息
    auth.logout()
    
    // 跳转到登录页
    router.push('/login')
    
    ElMessage.success('已成功退出登录')
  } catch {
    // 用户取消操作
  }
}
</script>

<style scoped>
.nav-container {
  position: fixed;
  left: 0;
  top: 0;
  height: 100vh;
  width: 240px;
  background: linear-gradient(180deg, #1a237e 0%, #0d47a1 100%);
  box-shadow: 4px 0 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  z-index: 1000;
}

.logo-section {
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 20px;
  margin-bottom: 20px;
}

.logo-section img {
  height: 40px;
}

.nav-menu {
  border: none;
  background: transparent !important;
}

/* 主菜单项样式 */
.menu-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 0 12px;
}

/* 子菜单项样式 */
.submenu-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding-left: 12px;
}

.dot {
  width: 6px;
  height: 6px;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 50%;
}

/* Element Plus 菜单样式覆盖 */
:deep(.el-menu) {
  background-color: transparent !important;
}

:deep(.el-menu-item),
:deep(.el-sub-menu__title) {
  height: 50px;
  line-height: 50px;
  background-color: transparent !important;
  border-radius: 8px;
  margin: 4px 12px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

:deep(.el-menu-item:hover),
:deep(.el-sub-menu__title:hover) {
  background: rgba(255, 255, 255, 0.1) !important;
  transform: translateX(5px);
}

:deep(.el-menu-item.is-active) {
  background: rgba(255, 255, 255, 0.15) !important;
  color: #ffffff !important;
  font-weight: 500;
}

:deep(.el-sub-menu__title) {
  padding-left: 12px !important;
}

:deep(.el-icon) {
  font-size: 20px;
}

/* 子菜单弹出框样式 */
:deep(.el-menu--popup) {
  background: linear-gradient(180deg, #1a237e 0%, #0d47a1 100%) !important;
  border-radius: 8px;
  padding: 4px;
  min-width: 160px;
}

:deep(.el-menu--popup .el-menu-item) {
  height: 40px;
  line-height: 40px;
  margin: 4px;
}

:deep(.el-menu--popup .el-menu-item:hover) {
  background: rgba(255, 255, 255, 0.1) !important;
}

/* 滚动条样式 */
.nav-menu {
  overflow-y: auto;
  overflow-x: hidden;
  height: calc(100vh - 200px); /* 为用户信息区域预留空间 */
}

.nav-menu::-webkit-scrollbar {
  width: 4px;
}

.nav-menu::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 2px;
}

.nav-menu::-webkit-scrollbar-track {
  background: transparent;
}

/* 用户信息区域样式 */
.user-section {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.2);
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  padding: 16px 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid rgba(255, 255, 255, 0.2);
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-details {
  flex: 1;
  min-width: 0;
}

.username {
  color: #ffffff;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.user-role {
  color: rgba(255, 255, 255, 0.7);
  font-size: 12px;
}

.user-actions {
  display: flex;
  justify-content: center;
}

.logout-btn {
  color: rgba(255, 255, 255, 0.8) !important;
  padding: 8px 16px !important;
  border-radius: 6px;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 6px;
}

.logout-btn:hover {
  background: rgba(255, 255, 255, 0.1) !important;
  color: #ffffff !important;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .nav-container {
    transform: translateX(-100%);
    transition: transform 0.3s ease;
  }
  
  /* 如果需要在移动端显示导航栏，可以添加一个类来控制 */
  .nav-container.mobile-visible {
    transform: translateX(0);
  }
}

</style>